import java.io.*;

/**
 * 
 * @author Jesse en Jeroen
 *
 */
public class Servlet 
{
	private Response res;
	private Request req;
	private String documentRoot;
	private File file;
	private String extention;
	
	public Servlet(Request req, Response res, String dr)
	{
		this.res = res;
		this.req = req;
		documentRoot = dr;
		System.out.println("\nStarting Servlet");
		
		if (this.req.getMETHOD().equals("GET")){
			doGet();
		}
	}
	private void doGet(){
		String path = documentRoot + _fetchUri(req.getURI());
		int length = path.length();
		extention = path.substring(length - 5, length);
		System.out.println(extention);
		System.out.println("Executing GET");
		try{
			System.out.println("Requesting file: "+path);
			
			
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file = new File(path)));
			ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
			int c;
			while ((c = bis.read()) != -1){
				bytearray.write(c);
			}
			bis.close();
			res.setBYTES(bytearray.toByteArray());
			bytearray.close();
			res.setCODE("200");
			res.setREASON("OK");
			res.setType(extention);
		}catch (FileNotFoundException fnfe){
			// 404 error terugsturen met response
			res.setCODE("404");
			res.setREASON("File Not Found");
			byte[] outputBytes = this.get404().getBytes();
			res.setBYTES(outputBytes);
			
			
			System.out.println("404 File Not Found");
		}catch (IOException ioe){
			// 500 Server error terugsturen
			res.setCODE("500");
			res.setREASON("Server error");
			byte[] outputBytes = this.get500().getBytes();
			res.setBYTES(outputBytes);
			System.out.println("500 Server error");
		}
	}
	private String _fetchUri(String uri){
		if (uri.endsWith("/")){
			uri += "index.html";
		}return uri;
	}
	
	public String get404()
	{
		String output = "<html>" +
				"<head><title>404</title></head>" +
				"<body>" +
				"<p>There has been an 404-error. This means that a requested file has not been found</p>" +
				"</body></html>";
		return output;
	}
	
	public String get500()
	{
		String output = "<html>" +
				"<head><title>500</title></head>" +
				"<body>" +
				"<p>There has been a server-error. Please try again later.</p>" +
				"</body></html>";
		return output;
	}
}
